package AEF::MEFProcessor;


use Modern::Perl;
use Moose;
use Log::Log4perl qw( :easy );

require AEF::AEFProcessor;

extends 'AEF::AEFProcessor';

has 'mefData' => (
	is => 'rw',
	isa => 'Str',
	default => sub{
		my $data = pack('vVvZ*', 1, 0x1b, 0x280, 
						'CA-VO Module Export File');
		return $data;
	},
);

has 'moduleName' => (
	is => 'rw',
	isa => 'Str',
	required => 1,
);

has 'inModule' => (
	is => 'rw',
	isa => 'Bool',
	default => 0,
);


override 'TypeMap' => sub
{
	my $self = shift;
	my $type = shift;
	if($type == 0x20)
	{
		return "Z*";
	}
	# we don't want any of the data to be mangled for this one
	# we want our module name parsed I guess
	# everything else we probably want to drop.
	return undef;
};

around 'RequireDataForType' => sub
{
	my $orig = shift;
	my $self = shift;
	my $type = shift;

	if($type == 0x20 || $self->inModule)
	{
		return 1;
	}
	return 0;
};

override 'ProcessBlock' => sub 
{
	my $self = shift;
	my ($type, $data_chunk, $ptr, $length) = @_;
	my $logger = get_logger();
	given($type)
	{
		when(0x20)
		{
			my ($module_name) = $data_chunk;
			$logger->debug("Encountered module $module_name");
			if($self->inModule)
			{
				$self->inModule(0);
				# write EOF
				$self->AddData(pack('vV', 0xffff, 0));
				$self->doneProcessing(1);
			}
			elsif($module_name eq $self->moduleName)
			{
				$self->inModule(1);
				my $data = pack('vVZ*', ($type, $length, $module_name));
				$self->AddData($data);
				# start capturing the data
			}
		}
		default
		{
			my $header_block = pack('vV', ($type, $length));
			$self->AddData($header_block, $data_chunk);
			# FIXME: what's the best way to build a big 
			# string
		}
	}
};

sub AddData
{
	my $self = shift;
	my @data = @_;
	for my $chunk (@data)
	{
		$self->mefData($self->mefData . $chunk);
	}
}


1;

no Moose;
